package com.soso.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.soso.dao.ModulesDao;
import com.soso.entity.Modules;
import com.soso.service.ModulesService;

@Service
public class ModulesImpl implements ModulesService{
	  @Autowired 
	  ModulesDao md;

	@Override
	public List<Modules> getAll(Integer id) {
		List<Modules> mlist=new ArrayList<>();
		if(StringUtils.isEmpty(id)) {
			mlist=md.findAll();
		}
		List<Modules> TreeNodes = new ArrayList<Modules>();
		for (Modules treeNode : mlist) {
			if (treeNode.getParentId()==null||treeNode.getParentId()==0) {
				TreeNodes.add(findChildren(treeNode, mlist));
			}
		}
		return TreeNodes;
	}

	
	@Override
	public Modules findChildren(Modules treeNode, List<Modules> treeList) {
		for (Modules item : treeList) {
			if(treeNode.getId()==item.getParentId()) {
				if(treeNode.getChildren()==null) {
					treeNode.setChildren(new ArrayList<Modules>());
				}
				treeNode.getChildren().add(findChildren(item, treeList));
			}
		}
		return treeNode;
	}

	/**
	 * 根据id查询
	 */
	@Override
	public Modules getById(Integer id) {
		return md.findById(id).orElse(null);
	}

	/**
	 * 删除
	 */
	@Override
	public Integer deletle(Integer id) {
		try {
			md.deleteById(id);
			return 1;
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * 添加和修改
	 */
	@Override
	public Integer save(Modules m) {
		if(md.saveAndFlush(m)!=null) {
			return 1;
		}else {
			return 0;
		}
		
	}



	
}